package com.epfresh.supplier.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.epfresh.api.constant.AppSupplyRouterConstant;
import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.RequestEntityMapSupply;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.StatusEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.ucrop.PhotoCore;
import com.epfresh.api.universalimageloader.core.ImageLoader;
import com.epfresh.api.universalimageloader.core.assist.ImageSize;
import com.epfresh.api.universalimageloader.core.imageaware.ImageViewAware;
import com.epfresh.api.utils.FileUtil;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.api.utils.T;
import com.epfresh.api.utils.VerificationUtils;
import com.epfresh.api.widget.CommonInputItem;
import com.epfresh.api.widget.PhotoUploadView;
import com.epfresh.pickerview.dialog.WheelDialog;
import com.epfresh.supplier.R;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.entity.Bank;
import com.epfresh.supplier.entity.ContentEntity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tencent.mmkv.MMKV;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BankActivity extends BaseActivity implements PhotoCore.PhotoResult {

    static final String TAG = "BankActivity";
    CommonInputItem ciId;
    CommonInputItem ciName;
    CommonInputItem ciBranchName;
    CommonInputItem ciUserName;
    CommonInputItem ciBankId;

    View vPic;
    PhotoUploadView pvUpload;
    View vAbout;
    TextView tvAbout;
    TextView vSure;
    TextView tvCache;
    View vWarning;

    ListView lvBankName;
    boolean nameFlag;

    List<Bank> bankList = new ArrayList<>();

    int type = -1;
    int cardCount = -1;

    String bankId = "";
    private PhotoCore photoCore;
    private String filePath = FileUtil.getImgCacheDir() + "/" + "bank";

    //1,个人,2,企业
    int userType = 1;

    Bank bank = new Bank();

    boolean isFirst;
    private LinearLayout llProgress;
    private String remark;
    private TextView tvRefuseContent;
    private RelativeLayout rlRefuseReason;
    private boolean isStore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isStore = MMKV.defaultMMKV().decodeBool("isStore");
        MMKV.defaultMMKV().encode("isStore", false);
        if (savedInstanceState != null) {
            getIntent().putExtra(Constant.TYPE, savedInstanceState.getInt(Constant.TYPE));
            getIntent().putExtra("card_count", savedInstanceState.getInt("card_count"));
            getIntent().putExtra("userType", savedInstanceState.getInt("userType"));
            getIntent().putExtra("isFirst", savedInstanceState.getBoolean("isFirst"));
        }
        isFirst = getIntent().getBooleanExtra("isFirst", false);
        type = getIntent().getIntExtra(Constant.TYPE, -1);
        cardCount = getIntent().getIntExtra("card_count", -1);
        userType = getIntent().getIntExtra("userType", 1);
        remark = getIntent().getStringExtra("remark");
        setContentView(R.layout.activity_bank);
        initView();

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt(Constant.TYPE, type);
        outState.putInt("card_count", cardCount);
        outState.putInt("userType", userType);
        outState.putBoolean("isFirst", isFirst);
        super.onSaveInstanceState(outState);
    }

    private void initView() {
        rlRefuseReason = findViewById(R.id.rl_refuse_reason);
        tvRefuseContent = findViewById(R.id.tv_refuse_content);
        llProgress = findViewById(R.id.ll_progress);
        llProgress.setVisibility(View.VISIBLE);
        vPic = findViewById(R.id.rl_pic);
        pvUpload = (PhotoUploadView) findViewById(R.id.pu_upload);

        int imgWidth = (LocalDisplay.SCREEN_WIDTH_PIXELS - LocalDisplay.dp2px(48)) / 2;
        int imgHeight = imgWidth * 204 / 282;

        ViewGroup.LayoutParams lp = pvUpload.getLayoutParams();

        lp.width = imgWidth;
        lp.height = imgHeight;

        pvUpload.setLayoutParams(lp);

        ciId = (CommonInputItem) findViewById(R.id.ci_card_id);
        ciBankId = (CommonInputItem) findViewById(R.id.ci_bank_id);
        ciName = (CommonInputItem) findViewById(R.id.ci_bank_name);
        ciBranchName = (CommonInputItem) findViewById(R.id.ci_bank_name_brance);
        ciUserName = (CommonInputItem) findViewById(R.id.ci_bank_card_user);
        vWarning = findViewById(R.id.ll_warning);
        vSure = (TextView) findViewById(R.id.tv_btn);
        tvCache = (TextView) findViewById(R.id.tv_save_cache);
        vSure.setOnClickListener(this);
        ciName.setOnClickListener(this);
        ivBack.setVisibility(View.VISIBLE);
        tvBack.setVisibility(View.VISIBLE);
        toolbarTitle.setText("申请开店");

        rightbtn.setText(getString(R.string.help));
        rightbtn.setVisibility(View.VISIBLE);
        rightbtn.setOnClickListener(this);
        rightbtn.setTextColor(0xff898989);
        tvAbout = (TextView) findViewById(R.id.tv_warning);
        tvAbout.setText(BaseApplication.getDoc().getServicePhone());

        updateView(userType);
        if (!TextUtils.isEmpty(remark)) {
            tvRefuseContent.setText(remark);
            rlRefuseReason.setVisibility(View.VISIBLE);
        }

        tvCache.setOnClickListener(this);
        if (type == -1) {
            ciBankId.setOnClickListener(null);
            vPic.setVisibility(View.GONE);
            ciBankId.setEnabled(false);
            ciBankId.showFlag(false);
        } else {
            ciBankId.setOnClickListener(this);
            vPic.setVisibility(View.VISIBLE);
            ciBankId.setEnabled(true);
            initPhotoCore();
        }


        if (cardCount > 0 && !getStoreInfo().isFirstOpen()) {//已经绑定银行卡
            updateCanNotEdit();
            //查找银行名称
            mHttpLoad();
            requestBankDetail();
        } else {
            final EditText content = (EditText) ciId.getContent();
            String digits = "01234567890 ";
            content.setKeyListener(DigitsKeyListener.getInstance(digits));
            content.addTextChangedListener(new TextWatcher() {
                int beforeTextLength = 0;
                int onTextLength = 0;
                boolean isChanged = false;

                int location = 0;// 记录光标的位置
                private char[] tempChar;
                private StringBuffer buffer = new StringBuffer();
                int konggeNumberB = 0;

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    onTextLength = s.length();
                    buffer.append(s.toString());
                    if (onTextLength == beforeTextLength || onTextLength <= 3 || isChanged) {
                        isChanged = false;
                        return;
                    }
                    isChanged = true;
                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    beforeTextLength = s.length();
                    if (buffer.length() > 0) {
                        buffer.delete(0, buffer.length());
                    }
                    konggeNumberB = 0;
                    for (int i = 0; i < s.length(); i++) {
                        if (s.charAt(i) == ' ') {
                            konggeNumberB++;
                        }
                    }
                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (isChanged) {
                        location = content.getSelectionEnd();
                        int index = 0;
                        while (index < buffer.length()) {
                            if (buffer.charAt(index) == ' ') {
                                buffer.deleteCharAt(index);
                            } else {
                                index++;
                            }
                        }

                        index = 0;
                        int konggeNumberC = 0;
                        while (index < buffer.length()) {
                            // if (index % 5 == 4) {
                            //      buffer.insert(index, ' ');
                            //      konggeNumberC++;
                            // }
                            if (index == 4 || index == 9 || index == 14 || index == 19) {
                                buffer.insert(index, ' ');
                                konggeNumberC++;
                            }
                            index++;
                        }

                        if (konggeNumberC > konggeNumberB) {
                            location += (konggeNumberC - konggeNumberB);
                        }

                        tempChar = new char[buffer.length()];
                        buffer.getChars(0, buffer.length(), tempChar, 0);
                        String str = buffer.toString();
                        if (location > str.length()) {
                            location = str.length();
                        } else if (location < 0) {
                            location = 0;
                        }

                        content.setText(str);
                        Editable etable = content.getText();
                        Selection.setSelection(etable, location);
                        isChanged = false;
                    }
                }
            });


            if (getStoreInfo().isFirstOpen()) {
                requestBankDetail();

                tvCache.setVisibility(View.VISIBLE);
                vSure.setVisibility(View.VISIBLE);
                vSure.setText("提交审核");
            } else {
                tvCache.setVisibility(View.GONE);
                vSure.setVisibility(View.VISIBLE);
                vSure.setText("保存");
            }
            mHttpLoad();
        }
        if (isStore) {
            toolbarTitle.setText("收款账户");
            llProgress.setVisibility(View.GONE);
        }

    }

    public void updateCanNotEdit() {
        vPic.setVisibility(View.GONE);
        vSure.setVisibility(View.GONE);
        tvCache.setVisibility(View.GONE);
        vWarning.setVisibility(View.VISIBLE);

        vWarning.setOnClickListener(this);
        ciBankId.setOnClickListener(null);
        ciBankId.setEditable(false);
//            findViewById(R.id.hint).setVisibility(View.GONE);
        findViewById(R.id.v_bottom).setVisibility(View.GONE);
        findViewById(R.id.iv_add_audit).setVisibility(View.INVISIBLE);

        ciId.setTextEnabled(false);
        ciName.setTextEnabled(false);
        ciBranchName.setTextEnabled(false);
        ciBranchName.setEnabled(false);
        ciUserName.setTextEnabled(false);

    }

    public void updateView(int type) {
        //fix switch personal / company status not change bug
        this.userType = type;
        if (this.type == -1) {//个人认证
            ciUserName.setText("持卡人姓名", 0);
            ciUserName.setContentHintText("请填写持卡人姓名");
            ciBankId.setContentText("个人类型");
            bank.setType("1");
            return;
        }
        if (type == 1) {
            ciUserName.setTitleText("持卡人姓名");
            ciUserName.setContentHintText("请填写持卡人姓名");
            ciBankId.setContentText("个人类型");
            bank.setType("1");
        } else {
            ciUserName.setTitleText("企业名称");
            ciUserName.setContentHintText("请填写企业名称");
            ciBankId.setContentText("企业类型");
            bank.setType("2");
        }
    }

    private void initPhotoCore() {
        photoCore = new PhotoCore(this, this);
        photoCore.setResultHeight(200);
        photoCore.setResultWidth(200);
        pvUpload.setFilePath(new File(filePath + "_" + System.currentTimeMillis()).getPath());
        pvUpload.setOnClickListener(this);
    }

    public void updateBankName() {
        if (bankList != null && bankId != null && !"".equals(bankId)) {
            for (int i = 0; i < bankList.size(); i++) {
                if (bankId.equals(bankList.get(i).getBankId())) {
                    String bankName = bankList.get(i).getBankName();
                    ciName.setContentText(bankName);
                }
            }
        }
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.ci_bank_name:
                // 返回上一页
//                initName();
                openUnitDialog();
                break;
            case R.id.ci_bank_id:
                // 返回上一页
//                initName();
                // openTypeDialog();
                break;
            case R.id.tv_btn:
                save();
                break;
            case R.id.tv_save_cache:
                saveCache();
                break;
            case R.id.pu_upload:

                if (cardCount > 0 && !getStoreInfo().isFirstOpen()) {//已经绑定银行卡
                    return;
                }
                photoCore.showPhotoDialog(Uri.fromFile(new File(pvUpload.getFilePath())), pvUpload.getFilePath(), pvUpload.isFail());
                break;
            case R.id.rightbtn:
                help();
                break;
            case R.id.ll_warning:
                String servicePhone = BaseApplication.getDoc().getServicePhone();
                String[] split = servicePhone.split("：");
                if (split == null || split.length < 2) {
                    split = servicePhone.split(":");
                }
                if (split != null && split.length > 1) {
                    String s = split[split.length - 1];
                    s = s.replace("-", "");
                    s.replace("－", "");
                    if (VerificationUtils.isNumeric(s)) {
                        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + s));//调出来拨打页面；
                        startActivity(intent);
                    }
                }
                break;
            default:
                break;
        }
    }

    private void saveCache() {
        if (isContentEmpty()) {
            toast("请填写信息");
            return;
        }
        String branchName = ciBranchName.getContentText();
        String userName = ciUserName.getContentText();
        String id = ciId.getContentText();
        String name = ciName.getContentText();


        if (!VerificationUtils.isValid(userName)) {
            if (userType == 1) {
                toast(getString(R.string.illegal_input, "持卡人姓名"));
            } else {
                toast(getString(R.string.illegal_input, "企业名称"));
            }

            return;
        }

        bank.setBankBranchName(branchName);
        bank.setBankId(bankId);
        bank.setCardholderName(userName);
        bank.setBankName(name);
        bank.setCardNo(id);
        if (userType == 1) {
            bank.setType("1");
        } else {
            bank.setType("2");
        }
        if (pvUpload.getPhotoId() != null && !"".equals(pvUpload.getPhotoId())) {
            bank.setLicenseImgUrl(pvUpload.getUrl());
            bank.setLicenseImgId(pvUpload.getPhotoId());
        } else {
            bank.setLicenseImgUrl(null);
            bank.setLicenseImgId(null);
        }
        requestBank(bank, true);
    }

    private boolean isContentEmpty() {
//        if (!TextUtils.isEmpty(ciBankId.getContentText())) {
//            return false;
//        }
//
        if (!TextUtils.isEmpty(ciId.getContentText())) {
            return false;
        }

        if (!TextUtils.isEmpty(ciName.getContentText())) {
            return false;
        }

        if (!TextUtils.isEmpty(ciBranchName.getContentText())) {
            return false;
        }
        if (!TextUtils.isEmpty(ciUserName.getContentText())) {
            return false;
        }
        if (pvUpload.getPhotoId() != null && !"".equals(pvUpload.getPhotoId())) {
            return false;
        }

        return true;
    }


    private void help() {

        Intent intent = new Intent(this, WebActivity.class);
        intent.putExtra(Constant.KEY_WEB_URL, Constant.URL_HELP_ADD_BANK);
        intent.putExtra(Constant.KEY_WEB_TITLE, getString(R.string.help));
        startActivity(intent);

    }

    private void save() {
        String branchName = ciBranchName.getContentText();
        String userName = ciUserName.getContentText();
        String id = ciId.getContentText();
        String name = ciName.getContentText();

        if (TextUtils.isEmpty(id)) {
            toast("请输入卡号");
            return;
        }
        id = id.replace(" ", "");
        if (!(id.length() > 9)) {
            toast("请输入合法的卡号");
            return;
        }
        if (TextUtils.isEmpty(name)) {
            toast("请选择开户行");
            return;
        }
//        if (TextUtils.isEmpty(branchName)) {
//            toast("请输入支行名称");
//            return;
//        }
        if (!TextUtils.isEmpty(branchName) && !VerificationUtils.isValid(branchName)) {
            toast(getString(R.string.illegal_input, "支行名称"));
            return;
        }
        if (TextUtils.isEmpty(userName)) {
            if (userType == 1) {
                toast("请输入持卡人姓名");
            } else {
                toast("请输入企业名称");
            }

            return;
        }

        if (userType == 1) {
            if (userName.length() > 10) {
                toast("持卡人姓名不能多于10个字");
                return;
            }
        } else {
            if (userName.length() < 6 || userName.length() > 30) {
                toast("企业名称请输入6-30个字");
                return;
            }
        }

        if (!VerificationUtils.isValid(userName)) {
            if (userType == 1) {
                toast(getString(R.string.illegal_input, "持卡人姓名"));
            } else {
                toast(getString(R.string.illegal_input, "企业名称"));
            }
            return;

        }
        bank.setBankBranchName(branchName);
        bank.setBankId(bankId);
        bank.setCardholderName(userName);
        bank.setBankName(name);
        bank.setCardNo(id);
        if (pvUpload.getPhotoId() != null && !"".equals(pvUpload.getPhotoId())) {
            bank.setLicenseImgUrl(pvUpload.getUrl());
            bank.setLicenseImgId(pvUpload.getPhotoId());
        } else {
            bank.setLicenseImgUrl(null);
            bank.setLicenseImgId(null);
        }
        if (userType == 1) {
            bank.setType("1");
        } else {
            bank.setType("2");
        }

        requestBank(bank, false);
    }

    private void initName() {
        if (nameFlag) {
            lvBankName.setVisibility(View.GONE);
            nameFlag = false;
        } else {
            if (bankList != null) {
                lvBankName.setVisibility(View.VISIBLE);
                nameFlag = true;
            } else {
                T.toast("银行数据加载中，请稍等");
            }
        }
    }


    private ArrayList<Bank> options1Items = new ArrayList<Bank>();
    private WheelDialog pvOptions;

    public void openUnitDialog() {
        if (bankList == null || bankList.size() == 0) {
            T.toast("银行数据加载中，请稍等");
        }
        if (pvOptions == null) {
            pvOptions = new WheelDialog(this);
            pvOptions.setTitle("选择开户行");
            pvOptions.setOnoptionsSelectListener(new WheelDialog.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int option2, int options3) {
                    if (options1 < options1Items.size()) {
                        Bank bank = options1Items.get(options1);
                        ciName.setContentText(bank.getBankName());
                        bankId = bank.getBankId();
                    }

                }
            });
        }

        pvOptions.setTag(type);
        options1Items.clear();
        if (bankList != null) {
            options1Items.addAll(bankList);
            pvOptions.setPicker(options1Items);

            for (int i = 0; i < bankList.size(); i++) {
                Bank bank = bankList.get(i);
                if (bankId != null && !"".equals(bankId) && bankId.equals(bank.getBankId())) {
                    pvOptions.setSelectOptions(i);
                    break;
                }
            }
            pvOptions.show();
        } else {
            // toast("该城市没有市场");
        }
    }

    private ArrayList<String> typeItems = new ArrayList<String>();
    private WheelDialog typeOptions;

    public void openTypeDialog() {

        if (typeOptions == null) {
            typeOptions = new WheelDialog(this);
            typeOptions.setOnoptionsSelectListener(new WheelDialog.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int option2, int options3) {
                    if (options1 < typeItems.size()) {

                        String s = typeItems.get(options1);
                        ciBankId.setContentText(s);

                        if ("企业类型".equals(s)) {
                            bank.setType("2");
                            vPic.setVisibility(View.VISIBLE);
                            updateView(2);
                        } else {
                            bank.setType("1");
                            vPic.setVisibility(View.GONE);
                            updateView(1);
                        }


                    }

                }
            });
        }

        typeOptions.setTag(type);
        typeItems.clear();
        typeItems.add("企业类型");
        typeItems.add("个人类型");


        typeOptions.setPicker(typeItems);

        for (int i = 0; i < typeItems.size(); i++) {
            String bank = typeItems.get(i);
            if (bank != null && !"".equals(bank) && bank.equals(ciBankId.getContentText())) {
                typeOptions.setSelectOptions(i);
                break;
            }
        }
        typeOptions.show();

    }


    OnRequestListener<ContentEntity<Bank>> onRequestListener = new OnRequestListener<ContentEntity<Bank>>() {
        @Override
        public ContentEntity<Bank> jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, new TypeToken<ContentEntity<Bank>>() {
            }.getType());
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<ContentEntity<Bank>> response, Object tag) {
            ContentEntity<Bank> banks = response.getResponseElement();
            lvBankName = (ListView) findViewById(R.id.lv_bank_name);
            bankList = banks.getBanks();
//            lvBankName.setAdapter(new CommonAdapter<Bank>(mContext, bankList,
//                    R.layout.item_string) {
//                @Override
//                public void convert(final ViewHolder holder, final Bank bean) {
//                    holder.setText(R.id.tv_string, bean.getBankName());
//                    holder.setOnClickListener(R.id.tv_string, new View.OnClickListener() {
//                        @Override
//                        public void onClick(View view) {
//                            lvBankName.setVisibility(View.GONE);
//                            ciName.setContentText(bean.getBankName());
//                            bankId = bean.getBankId();
//                        }
//                    });
//
//                }
//            });
            if (cardCount > 0) {
                updateBankName();
            }
        }
    };

    /**
     * 加载银行名称数据
     */
    private void mHttpLoad() {
        RequestEntitySupply<Map<String, String>> data = new RequestEntitySupply<>();
        data.setCmd(AppSupplyRouterConstant.cmd_finance_settle_queryAllBank);
        data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
        Map<String, String> map = new HashMap<>();
        map.put("accountId", getUser().getAccountId());
        data.setParameters(map);
        request(data, AppSupplyRouterConstant.cmd_finance_settle_queryAllBank, onRequestListener);
    }


    public void requestBankDetail() {

        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(AppSupplyRouterConstant.cmd_store_store_bankCardInfo_view);
        RequestTag tag = new RequestTag();
        tag.tag = AppSupplyRouterConstant.cmd_store_store_bankCardInfo_view;
        tag.type = RequestTag.TYPE_CURRENT;
        request(RequestEntityMapSupply, tag, onBankDetailRequestListener);
    }

    private OnRequestListener<Bank> onBankDetailRequestListener = new OnRequestListener<Bank>() {
        @Override
        public Bank jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, Bank.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<Bank> response, Object tag) {

            hideProgressDialog();
            Bank responseElement = response.getResponseElement();

            bankId = responseElement.getBankId();
            if (isFirst) {
                ciId.setContentText(responseElement.getCardNo());
            } else {
                ciId.setContentText(responseElement.getHideCardNo());
            }
            ciId.setSelectionLast();
            ciName.setContentText(responseElement.getBankName());
            ciBranchName.setContentText(responseElement.getBankBranchName());
            ciUserName.setContentText(responseElement.getCardholderName());

            updateBankName();

            if (cardCount > 0 && !getStoreInfo().isFirstOpen()) {//已经绑定银行卡
                updateCanNotEdit();
            }
            if ("2".equals(responseElement.getType())) {
                vPic.setVisibility(View.VISIBLE);
            } else {
                vPic.setVisibility(View.GONE);
            }
            String licenseImgUrl = responseElement.getLicenseImgUrl();
            if (licenseImgUrl != null && !"".equals(licenseImgUrl)) {
                if ("2".equals(responseElement.getType())) {
                    vPic.setVisibility(View.VISIBLE);
                }
                pvUpload.setUrl(licenseImgUrl);
                ImageSize imageSize = new ImageSize(200, 200);
                ImageLoader.getInstance().displayImage(pvUpload.getUrl(), new ImageViewAware(pvUpload.getImagView()), pvUpload.getImageOption(), imageSize, null, null);
            } else {

            }
        }
    };

//    String cmdBank = "store/bankCardInfo/add";

    public void requestAudit() {

        RequestEntitySupply<Bank> RequestEntityMapSupply = new RequestEntitySupply<>();
        RequestEntityMapSupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_store_applyAudit);

        request(RequestEntityMapSupply, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_store_applyAudit, onAuditRequestListener);
    }

    private OnRequestListener<StatusEntity> onAuditRequestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();

        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {

            hideProgressDialog();
            StatusEntity responseElement = response.getResponseElement();
            if (responseElement.isSuccess()) {
//                toast(BaseApplication.getDoc().getBeenSubmitted());
//                getStoreInfo().setBankCardCount(1);
//                Intent intent = new Intent(BankActivity.this, StoreEnsureAndOpenActivity.class);
//                startActivity(intent);
//                finish();

                intoHome();

            } else {
                //没有数据


            }

        }
    };

    public void requestBank(Bank bank, boolean isScratch) {

        RequestEntitySupply<Bank> RequestEntityMapSupply = new RequestEntitySupply<>();
        RequestEntityMapSupply.setCmd(AppSupplyRouterConstant.cmd_store_store_bankCardInfo_modify);
        if (bank != null) {
            bank.setMerchantId(BaseApplication.getInstance().getMerchantId());
        }
        RequestEntityMapSupply.setParameters(bank);
        RequestTag tag = new RequestTag();
        tag.tag = AppSupplyRouterConstant.cmd_store_store_bankCardInfo_modify;
        tag.type = isScratch ? 1 : 0;
        request(RequestEntityMapSupply, tag, onBankRequestListener);
    }

    private OnRequestListener<StatusEntity> onBankRequestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();

        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {

            StatusEntity responseElement = response.getResponseElement();
            if (responseElement.isSuccess()) {
//                toast(BaseApplication.getDoc().getBeenSubmitted());
//                getStoreInfo().setBankCardCount(1);
//                Intent intent = new Intent(BankActivity.this, StoreEnsureAndOpenActivity.class);
//                startActivity(intent);
//                finish();

//                intoHome();
                if (isFirst) {
                    boolean isScratch = false;
                    if (tag != null && tag instanceof RequestTag) {
                        RequestTag rt = (RequestTag) tag;
                        isScratch = rt.type == 0 ? false : true;

                    }
                    if (isFirst && !isScratch) {

                        requestAudit();
                    } else {
                        toast("保存成功");
                        hideProgressDialog();
                    }
                } else {
                    hideProgressDialog();
                    intoStoreEnsureAndOpen();
                }
            } else {
                hideProgressDialog();
                //没有数据


            }

        }
    };

    public void intoHome() {
        Intent intent = new Intent(this, FirstPostAuditActivity.class);
        startActivity(intent);
        finish();
    }

    public void intoStoreEnsureAndOpen() {
        Intent intent = new Intent(BankActivity.this, StoreEnsureAndOpenActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void onSuccess(String path) {
        pvUpload.showImage();
        ImageSize imageSize = new ImageSize(200, 200);
        ImageLoader.getInstance().displayImage(path, new ImageViewAware(pvUpload.getImagView()), pvUpload.getImageOption(), imageSize, null, null);
        RequestTag tag = new RequestTag();
        tag.action = 0;
        tag.tag = "upload";
        pvUpload.uploadImage(this, pvUpload.getFilePath(), tag, true);
    }

    @Override
    public void onFail(String msg) {

    }

    @Override
    public void onReupload() {
        RequestTag tag = new RequestTag();
        tag.action = 0;
        tag.tag = "upload";
        pvUpload.uploadImage(this, pvUpload.getFilePath(), tag, true);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (photoCore != null) {
            photoCore.onResult(requestCode, resultCode, data);
        }
    }
}
